<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  

  
    
    
    <link href="https://fonts.loli.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">




  <meta name="keywords" content="NLP,sentiment analysis," />










<meta name="description" content="Sentiment Analysis（情感分析），又称倾向性分析，意见抽取（Opinion extraction），意见挖掘（Opinion mining），情感挖掘（Sentiment mining），主观分析（Subjectivity analysis），它是对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程，是NLP中一种常见应用。">
<meta name="keywords" content="NLP,sentiment analysis">
<meta property="og:type" content="article">
<meta property="og:title" content="sentiment analysis">
<meta property="og:url" content="http://codewithzhangyi.com/2019/03/11/sentiment-analysis/index.html">
<meta property="og:site_name" content="Zhang Yi">
<meta property="og:description" content="Sentiment Analysis（情感分析），又称倾向性分析，意见抽取（Opinion extraction），意见挖掘（Opinion mining），情感挖掘（Sentiment mining），主观分析（Subjectivity analysis），它是对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程，是NLP中一种常见应用。">
<meta property="og:locale" content="en">
<meta property="og:image" content="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/001.png?raw=true">
<meta property="og:image" content="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/002.png?raw=true">
<meta property="og:image" content="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/003.png?raw=true">
<meta property="og:image" content="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/004.png?raw=true">
<meta property="og:image" content="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/005.png?raw=true">
<meta property="og:updated_time" content="2019-04-24T03:05:20.559Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="sentiment analysis">
<meta name="twitter:description" content="Sentiment Analysis（情感分析），又称倾向性分析，意见抽取（Opinion extraction），意见挖掘（Opinion mining），情感挖掘（Sentiment mining），主观分析（Subjectivity analysis），它是对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程，是NLP中一种常见应用。">
<meta name="twitter:image" content="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/001.png?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codewithzhangyi.com/2019/03/11/sentiment-analysis/"/>






<script data-ad-client="ca-pub-2691877571661707" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  <title>sentiment analysis | Zhang Yi</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhang Yi</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle" style="color:#fff">
    <button>MENU</button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-projects">
          <a href="/projects/" rel="section">
            
            Projects
          </a>
        </li>
      
        
        <li class="menu-item menu-item-blog">
          <a href="/blog/" rel="section">
            
            Blog
          </a>
        </li>
      
        
        <li class="menu-item menu-item-activity">
          <a href="/activity/" rel="section">
            
            Activity
          </a>
        </li>
      
        
        <li class="menu-item menu-item-list-100">
          <a href="/list-100/" rel="section">
            
            List 100
          </a>
        </li>
      
        
        <li class="menu-item menu-item-friends">
          <a href="/friends/" rel="section">
            
            Friends
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://codewithzhangyi.com/2019/03/11/sentiment-analysis/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ZhangYi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhang Yi">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">sentiment analysis</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-03-11T23:49:45+08:00">
                2019-03-11
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/03/11/sentiment-analysis/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2019/03/11/sentiment-analysis/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>visitors
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Sentiment Analysis（情感分析），又称倾向性分析，意见抽取（Opinion extraction），意见挖掘（Opinion mining），情感挖掘（Sentiment mining），主观分析（Subjectivity analysis），它是对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程，是NLP中一种常见应用。</p>
<a id="more"></a>
<p>大致有以下几种应用场景：</p>
<p><strong>商品评价</strong> </p>
<p>在上网购物司空见惯的时代，购物评价铺天盖地，淘宝/京东/大众点评/…，客户的评价（好评positive/差评negative）变得对消费者、店家和app平台越来越重要。很多商户需要及时分析自家产品的评价，发现问题进行产品优化。</p>
<p><strong>社交账号留言</strong> </p>
<p>比如在微博上有很多大V或明星要做评控，所以短时间内处理大量评论成为了需求。例如反黑一直是饭圈比较头痛的事情，目前的做法是靠人工进行过滤，Sentiment Analysis就能智能反黑，用数据科学碾压竞争者。</p>
<p><strong>舆情分析</strong> </p>
<p>利用公共信息来判断趋势，比如新政策的出台是否受民众喜欢，公众对选举候选人的看法如何。</p>
<p><strong>趋势预测</strong></p>
<p>根据舆论预测选举结果；根据消费者信息指数预测市场趋势；早在2010年，就有学者指出，依靠Twitter公开信息的情感分析来预测股市的涨落，准确率高达87.6%！</p>
<p>Sentiment Analysis的本质是表达一种态度/观点（attitude） ，表达观点包含以下3个元素：</p>
<ol>
<li><strong>Holder / source of attitude（ = 持有观点的人 ）</strong></li>
<li><strong>Aspect / target of attitude（ = 观点的角度 ）</strong></li>
<li><strong>Type of attitude（ = 观点的情绪 ）</strong><ul>
<li>positive, negative</li>
<li>star rating (⭐ ~ ⭐⭐⭐⭐⭐)</li>
<li>hate, dislike, don’t care, Like, love (make choice)</li>
</ul>
</li>
</ol>
<p>Sentiment Analysis 的常见处理方式有以下几种：</p>
<ul>
<li><p><strong>docs -based：</strong> 整个观点文本直接判断</p>
</li>
<li><p><strong>sentences / phrases -based：</strong> 将文本拆成句子或短语再进行观点和情绪判断 </p>
</li>
<li><p><strong>aspects/targets/attributes -based：</strong> 先做观点抽取，再做情绪判断。</p>
</li>
</ul>
<p>因此，我们面临的情感分析任务包括如下几类：</p>
<ol>
<li><p><strong>Simplest task:</strong> Is the attitude of this text positive or negative?</p>
<p>基于整段文字/句子/短语 直接判断正负向情绪</p>
</li>
<li><p><strong>More complex:</strong> Rank the attitude of this text from 1 to 5</p>
<p>基于整段文字/句子/短语 直接判断情绪层次</p>
</li>
<li><p><strong>Advanced (eg. Aspect-based):</strong> Detect the target, source, or complex attitude types</p>
<p>先判断存在哪些观点的角度，再判断情绪倾向</p>
</li>
</ol>
<p>目前NLP被研究的最多的两种语言是英文和中文，英文在网上搜有很多好用的工具在此不做介绍。这里主要介绍对中文文本的情感分析。</p>
<h2 id="情感倾向分析"><a href="#情感倾向分析" class="headerlink" title="情感倾向分析"></a>情感倾向分析</h2><p>一般我们看评价的时候，如果一个商品好评多，我们可能买的更放心。下面是些关于某电影的评价：<img src="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/001.png?raw=true" alt=""> </p>
<p>公开的sentiment analysis体验接口，可以随意感受一下：</p>
<ul>
<li><p><a href="https://ai.qq.com/product/nlpemo.shtml" target="_blank" rel="noopener">腾讯</a> </p>
</li>
<li><p><a href="https://ai.baidu.com/tech/nlp/sentiment_classify" target="_blank" rel="noopener">百度</a> （推荐👍虽然不像我的风格，但这块百度做的还可以）</p>
<p><img src="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/002.png?raw=true" alt=""></p>
</li>
</ul>
<h3 id="开源-好用的工具"><a href="#开源-好用的工具" class="headerlink" title="开源/好用的工具"></a>开源/好用的工具</h3><h4 id="SnowNLP-（🔗链接）"><a href="#SnowNLP-（🔗链接）" class="headerlink" title="SnowNLP （🔗链接）"></a>SnowNLP （<a href="https://github.com/isnowfy/snownlp" target="_blank" rel="noopener">🔗链接</a>）</h4><p>GitHub上有开源做情感分析的好用的python包，我们来感受一下。首先请确保自己已经 <strong>‘pip install snownlp’</strong> ，对于nlp选手，这个包应该很熟悉了。不仅可以做情感分析，还可以做中文分词、词性标注、提取关键字等等。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> snownlp <span class="keyword">import</span> SnowNLP</span><br><span class="line"></span><br><span class="line">s = SnowNLP(<span class="string">u'这个东西真心很赞'</span>)</span><br><span class="line">print(s.sentiments)    <span class="comment"># 0.9769551298267365 positive的概率</span></span><br></pre></td></tr></table></figure>
<p>非常简单，就3行code解决。再来试试其他：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">s = SnowNLP(<span class="string">u'这个东西真心很赞，速度非常快，隔天到，送货到家，快递员服务态度很好，值得推荐，点个赞！'</span>)</span><br><span class="line">print(s.sentiments)    <span class="comment"># 0.9998864907454681 positive的概率</span></span><br><span class="line"></span><br><span class="line">s = SnowNLP(<span class="string">u'布料不好，不建议购买'</span>)</span><br><span class="line">print(s.sentiments)    <span class="comment"># 0.11886826035520526 positive的概率</span></span><br><span class="line"></span><br><span class="line">s = SnowNLP(<span class="string">u'食物很美味，但是服务员的态度很差劲！总体还可以吧。'</span>)</span><br><span class="line">print(s.sentiments)    <span class="comment"># 0.42427513441222864 positive的概率</span></span><br></pre></td></tr></table></figure>
<p>第二比第一句的正向评论更多，因此positive的概率也更大了。第三句属于负面评价，因此分数越接近0为负面，接近1为正面。</p>
<p>SnowNLP的优点是可以拿自己的数据去训练这个分类器，缺点是在长文本分析时，尤其是出现多个观点时，会有预测不准的情况。</p>
<p>当评价是长文本，也可以先做分句，再对每个句子进行情感分析：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">s = SnowNLP(<span class="string">u'食物很美味，但是服务员的态度很差劲！总体还可以吧。'</span>)</span><br><span class="line"><span class="keyword">for</span> sentence <span class="keyword">in</span> s.sentences:</span><br><span class="line">	print(sentence)</span><br><span class="line">	sentc = SnowNLP(sentence)</span><br><span class="line">	print(sentc.sentiments)</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 食物很美味</span></span><br><span class="line"><span class="comment"># 0.7625799472162259</span></span><br><span class="line"><span class="comment"># 但是服务员的态度很差劲</span></span><br><span class="line"><span class="comment"># 0.059144753698306296</span></span><br><span class="line"><span class="comment"># 总体还可以吧</span></span><br><span class="line"><span class="comment"># 0.8182792359070481</span></span><br></pre></td></tr></table></figure>
<h4 id="百度API"><a href="#百度API" class="headerlink" title="百度API"></a>百度API</h4><p>这里的APP_ID、API_KEY、SECRET_KEY需要自己申请，传送门：<a href="https://ai.baidu.com/docs#/Begin/top" target="_blank" rel="noopener">开发指南</a> 。这样就可以免费用百度提供的接口了，目前还挺准的，而且最大可接受2048字节，目前缺点是有QPS=5限制，但也比人判断快多了。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> aip <span class="keyword">import</span> AipNlp</span><br><span class="line"></span><br><span class="line"><span class="string">""" 你的 APPID AK SK """</span></span><br><span class="line">APP_ID = <span class="string">'15593833'</span></span><br><span class="line">API_KEY = <span class="string">'PBW2w1dveS7x3YMecKSZW'</span></span><br><span class="line">SECRET_KEY = <span class="string">'AOE75EWZqeI6kM7WMXKesq8i6FzQ'</span></span><br><span class="line"></span><br><span class="line">client = AipNlp(APP_ID, API_KEY, SECRET_KEY)</span><br><span class="line">result=client.sentimentClassify(<span class="string">'我真的觉得武林外传超级好看！每个角色都超级喜欢！一年最少看三遍！老白说上一句我就能接下一句！'</span>)</span><br><span class="line">print(result)</span><br><span class="line"></span><br><span class="line"><span class="comment"># &#123;'log_id': 4474874689828720427, 'text': '我真的觉得武林外传超级好看！每个角色都超级喜欢！一年最少看三遍！老白说上一句我就能接下一句！', 'items': [&#123;'negative_prob': 0.0638882, 'sentiment': 2, 'positive_prob': 0.936112, 'confidence': 0.858026&#125;]&#125;</span></span><br></pre></td></tr></table></figure>
<p>这里的返回结果有negative_prob，表示这段话为负面情绪的概率。sentiment=2表示判断结果为正面情绪，为0表示为负面，为1表示为中立情绪。</p>
<p>如果是批量请求：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env  python</span></span><br><span class="line"><span class="comment">#  -*-  coding:  utf-8  -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span>  aip  <span class="keyword">import</span>  AipNlp</span><br><span class="line"><span class="keyword">import</span>  pandas  <span class="keyword">as</span>  pd</span><br><span class="line"><span class="keyword">import</span>  time</span><br><span class="line"></span><br><span class="line"><span class="string">"""  你的  APPID  AK  SK  """</span></span><br><span class="line">APP_ID  =  <span class="string">'155934'</span></span><br><span class="line">API_KEY  =  <span class="string">'PBW2w1dveS7x3YcKSZW0V7'</span></span><br><span class="line">SECRET_KEY  =  <span class="string">'AOE75EWZqeI6kM7Kesq8i6FzQruDI'</span></span><br><span class="line">client  =  AipNlp(APP_ID,  API_KEY,  SECRET_KEY)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 请求文件</span></span><br><span class="line">source_file  =  <span class="string">"请求文件路径"</span></span><br><span class="line">source_df  =  pd.read_excel(source_file)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">comments  =  []</span><br><span class="line">neg_probs  =  []</span><br><span class="line">pos_probs  =  []</span><br><span class="line">confidences  =  []</span><br><span class="line">sentiments  =  []</span><br><span class="line">complete_count  =  <span class="number">0</span></span><br><span class="line"><span class="comment">#  请求错误统计</span></span><br><span class="line">err_count  =  <span class="number">0</span></span><br><span class="line">err_comment  =  []</span><br><span class="line">start_time  =  time.time()</span><br><span class="line"><span class="comment">#  循环请求</span></span><br><span class="line">i  =  <span class="number">0</span></span><br><span class="line"><span class="keyword">while</span>  i  &lt;  len(source_df):</span><br><span class="line">        comment  =  source_df[<span class="string">"comment_content"</span>][i]</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">                query_result  =  client.sentimentClassify(comment[:<span class="number">1024</span>])</span><br><span class="line">        <span class="keyword">except</span>  Exception  <span class="keyword">as</span>  e:</span><br><span class="line">                print(<span class="string">"query_result:&#123;&#125;"</span>.format(query_result))</span><br><span class="line">                print(<span class="string">"#######请求过程存在问题#######"</span>)</span><br><span class="line">                err_count  +=  <span class="number">1</span></span><br><span class="line">                err_comment.append(comment)</span><br><span class="line">                i  +=  <span class="number">1</span></span><br><span class="line">                <span class="keyword">continue</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">                result  =  query_result[<span class="string">'items'</span>][<span class="number">0</span>]</span><br><span class="line">                neg_prob  =  result[<span class="string">'negative_prob'</span>]</span><br><span class="line">                pos_prob  =  result[<span class="string">'positive_prob'</span>]</span><br><span class="line">                confidence  =  result[<span class="string">'confidence'</span>]</span><br><span class="line">                sentiment  =  result[<span class="string">'sentiment'</span>]</span><br><span class="line">        <span class="keyword">except</span>  KeyError  <span class="keyword">as</span>  e:</span><br><span class="line">                print(<span class="string">"#######请求QPS限制#######"</span>)</span><br><span class="line">                print(<span class="string">"i=&#123;&#125;"</span>.format(i))</span><br><span class="line">                <span class="keyword">continue</span></span><br><span class="line">        i  +=  <span class="number">1</span></span><br><span class="line">        comments.append(comment)</span><br><span class="line">        neg_probs.append(neg_prob)</span><br><span class="line">        pos_probs.append(pos_prob)</span><br><span class="line">        confidences.append(confidence)</span><br><span class="line">        sentiments.append(sentiment)</span><br><span class="line">        complete_count  +=  <span class="number">1</span></span><br><span class="line">        print(<span class="string">"总共：&#123;&#125;条"</span>.format(len(source_df)))</span><br><span class="line">        print(<span class="string">"请求完成:  &#123;&#125;条"</span>.format(complete_count))</span><br><span class="line">        print(<span class="string">"完成进度：&#123;&#125;%"</span>.format(round(complete_count  /  len(source_df)  *  <span class="number">100</span>,  <span class="number">2</span>)))</span><br><span class="line">        cost_mins  =  (time.time()  -  start_time)  /  <span class="number">60</span></span><br><span class="line">        print(<span class="string">"累计用时：&#123;&#125;分钟"</span>.format(round(cost_mins,  <span class="number">2</span>)))</span><br><span class="line">        avg_query_time  =  complete_count  /  cost_mins</span><br><span class="line">        <span class="comment">#  print("每条请求平均用时：&#123;&#125;".format(avg_query_time))</span></span><br><span class="line">        left_mins  =  (len(source_df)  -  complete_count  -  err_count)  /  avg_query_time</span><br><span class="line">        print(<span class="string">"预计还需：&#123;&#125;分钟"</span>.format(round(left_mins,  <span class="number">2</span>)))</span><br><span class="line">        print(<span class="string">"\n"</span>)</span><br><span class="line"></span><br><span class="line">print(<span class="string">"所有请求完成！"</span>)</span><br><span class="line">print(<span class="string">"请求总数量：&#123;&#125;"</span>.format(len(source_df)))</span><br><span class="line">print(<span class="string">"请求过程中存在问题的数量：&#123;&#125;"</span>.format(err_count))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#  保存结果</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 请求成功的结果保存</span></span><br><span class="line">desti_df  =  pd.DataFrame()</span><br><span class="line">desti_df[<span class="string">"comment"</span>]  =  comments</span><br><span class="line">desti_df[<span class="string">"neg_probs"</span>]  =  neg_probs</span><br><span class="line">desti_df[<span class="string">"pos_probs"</span>]  =  pos_probs</span><br><span class="line">desti_df[<span class="string">"confidences"</span>]  =  confidences</span><br><span class="line">desti_df[<span class="string">"sentiments"</span>]  =  sentiments</span><br><span class="line">desti_file  =  <span class="string">"请求结果保存路径"</span></span><br><span class="line">desti_df.to_excel(desti_file, engine=<span class="string">'xlsxwriter'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 请求失败的结果保存</span></span><br><span class="line">err_df  =  pd.DataFrame()</span><br><span class="line">err_file  =  <span class="string">"请求结果报错保存路径"</span></span><br><span class="line">err_df[<span class="string">"comment"</span>] = err_comment</span><br><span class="line">err_df.to_excel(err_file, engine=<span class="string">'xlsxwriter'</span>) <span class="comment"># 如果请求接口里有奇怪字符，保存文件时就使用, engine='xlsxwriter'</span></span><br></pre></td></tr></table></figure>
<h3 id="baseline-model"><a href="#baseline-model" class="headerlink" title="baseline model"></a>baseline model</h3><p>关于评价分析最经典的就是kaggle的电影评价题，<a href="https://www.kaggle.com/c/word2vec-nlp-tutorial/data" target="_blank" rel="noopener">Bag of Words Meets Bags of Popcorn</a> ，预测一段评论是positive还是negative。稍后会专门为这个比赛写一篇。</p>
<p>可惜整个数据集都是英文的。下面几个为中文的数据集，非常珍贵，供参考：</p>
<p><a href="https://github.com/brightmart/nlp_chinese_corpus" target="_blank" rel="noopener">nlp_chinese_corpus</a><br><a href="http://www.nlpir.org/wordpress/category/corpus%E8%AF%AD%E6%96%99%E5%BA%93/" target="_blank" rel="noopener">自然语言处理与信息检索共享平台</a><br><a href="https://github.com/FannyChung/Sentiment-Analysis" target="_blank" rel="noopener">爬取商品评论并对商品评论进行情感分类</a> </p>
<p>其他开源项目参考：</p>
<ul>
<li><a href="https://github.com/baidu/Senta" target="_blank" rel="noopener">baidu 的 Senta</a> </li>
<li><a href="https://github.com/chaoming0625/SentimentPolarityAnalysis" target="_blank" rel="noopener">SentimentPolarityAnalysis</a> </li>
<li><a href="https://github.com/cjhutto/vaderSentiment" target="_blank" rel="noopener">vaderSentiment</a> </li>
</ul>
<h2 id="评论观点抽取-Aspect-Based"><a href="#评论观点抽取-Aspect-Based" class="headerlink" title="评论观点抽取  Aspect-Based"></a>评论观点抽取  Aspect-Based</h2><p>很多时候，观点经常是多角度的。一段评价可能同时有正面情绪和负面情绪，同时表达了多个观点：</p>
<blockquote>
<p>食物很美味，但是服务员的态度很差劲！总体还可以吧。</p>
</blockquote>
<p>这条评价里对食物的观点是positive的，对服务的观点是negative的，提及了两个维度。此时对整个评价做简单的分类是不够的。</p>
<p>Aspect / target of attitude（ = 观点的角度 ） </p>
<ul>
<li>single dimension 单个角度 </li>
<li>many dimensions 多个角度 （food, price, service,……根据不同的产品会有不同的角度）</li>
</ul>
<p><img src="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/003.png?raw=true" alt=""></p>
<p>下面是关于购物评价的 Aspects-based sentiment analysis：</p>
<p><img src="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/004.png?raw=true" alt=""> </p>
<p>这张图内有两个步骤，首先进行观点抽取，这里有关于价格、服务、口味等观点；其次再进行观点的正负面预测，在最右侧一栏的结果展示里。</p>
<p>给一个百度的观点抽取体验接口：<a href="https://ai.baidu.com/tech/nlp/comment_tag" target="_blank" rel="noopener">传送门</a> </p>
<p><img src="https://github.com/YZHANG1270/Markdown_pic/blob/master/2019/03/sentiment/005.png?raw=true" alt=""></p>
<p>里面已经有13类行业的各种观点预料训练出来的模型，比如有酒店、美食、房产、汽车等行业。当你把评价输入进去之后，分析结果会把各观点以及情绪都总结出来。</p>
<h5 id="AI-Challenger-全球AI挑战赛"><a href="#AI-Challenger-全球AI挑战赛" class="headerlink" title="AI Challenger 全球AI挑战赛"></a>AI Challenger 全球AI挑战赛</h5><p>2018的AI Challenger有一个是关于观点抽取的：细粒度用户评论情感分析。</p>
<ul>
<li>官网：<a href="https://challenger.ai/" target="_blank" rel="noopener">https://challenger.ai/</a></li>
<li>官方的baseline：<a href="https://github.com/AIChallenger/AI_Challenger_2018" target="_blank" rel="noopener">AI_Challenger_2018</a> </li>
<li>开源的解决方案：<a href="https://www.j4ml.com/t/50767" target="_blank" rel="noopener">AI Challenger 2018 文本挖掘类竞赛相关解决方案及代码汇总</a></li>
<li>数据集下载：<a href="https://drive.google.com/file/d/1OInXRx_OmIJgK3ZdoFZnmqUi0rGfOaQo/view" target="_blank" rel="noopener">传送门</a> </li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>打赏2块钱，帮我买杯咖啡，继续创作，谢谢大家！☕~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="ZhangYi WeChat Pay"/>
        <p>WeChat Pay</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/NLP/" rel="tag"># NLP</a>
          
            <a href="/tags/sentiment-analysis/" rel="tag"># sentiment analysis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/01/论文笔记-Convolutional-Sequence-to-Sequence-Learning/" rel="next" title="论文笔记 - Convolutional Sequence to Sequence Learning">
                <i class="fa fa-chevron-left"></i> 论文笔记 - Convolutional Sequence to Sequence Learning
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/12/pos/" rel="prev" title="POS tagging 词性标注 之 武林外传版">
                POS tagging 词性标注 之 武林外传版 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-2691877571661707"
     data-ad-slot="1301633292"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="ZhangYi" />
            
              <p class="site-author-name" itemprop="name">ZhangYi</p>
              <p class="site-description motion-element" itemprop="description">花时间做那些别人看不见的事~！</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/YZHANG1270" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:YZHANG1270@gmail.com" target="_blank" title="邮箱">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/p/1005053340707810?is_all=1" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#情感倾向分析"><span class="nav-text">情感倾向分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#开源-好用的工具"><span class="nav-text">开源/好用的工具</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#SnowNLP-（🔗链接）"><span class="nav-text">SnowNLP （🔗链接）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#百度API"><span class="nav-text">百度API</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#baseline-model"><span class="nav-text">baseline model</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#评论观点抽取-Aspect-Based"><span class="nav-text">评论观点抽取  Aspect-Based</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#AI-Challenger-全球AI挑战赛"><span class="nav-text">AI Challenger 全球AI挑战赛</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ZhangYi</span>

  
</div>








  <div class="footer-custom">All content under <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/">CC BY-NC-ND 4.0</a></div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      visitors
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>


  


  
  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://codewithzhangyi.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://codewithzhangyi.com/2019/03/11/sentiment-analysis/';
          this.page.identifier = '2019/03/11/sentiment-analysis/';
          this.page.title = 'sentiment analysis';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://codewithzhangyi.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  


  

  

</body>
</html>
